package com.example.springboot.config;

import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.SQLParameter;
import org.beetl.sql.core.kit.EnumKit;
import org.beetl.sql.core.mapping.BeanProcessor;
import org.beetl.sql.core.mapping.type.JavaSqlTypeHandler;
import org.beetl.sql.core.mapping.type.TypeParameter;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

public class LocalDateTimeBeanProcessor extends BeanProcessor {
    public LocalDateTimeBeanProcessor(SQLManager sm) {
        super(sm);
        this.handlers.put(LocalDateTime.class, new JavaSqlTypeHandler() {
            @Override
            public Object getValue(TypeParameter typePara) throws SQLException {
                Timestamp ts = typePara.getRs().getTimestamp(typePara.getIndex());
                return ts == null ? null : ts.toLocalDateTime();
            }
        });
    }

    @Override
    public void setPreparedStatementPara(String sqlId, PreparedStatement ps, List<SQLParameter> objList) throws SQLException {
        for(int i = 0; i < objList.size(); ++i) {
            SQLParameter para = (SQLParameter)objList.get(i);
            Object o = para.value;
            if (o == null) {
                ps.setObject(i + 1, o);
            } else {
                Class c = o.getClass();
                if (c == LocalDateTime.class) {
                    LocalDateTime d = (LocalDateTime)o;
                    ps.setTimestamp(i + 1, Timestamp.valueOf(d));
                } else {
                    if ((this.dbType == 2 || this.dbType == 3 || this.dbType == 6) && c == Date.class) {
                        o = new Timestamp(((Date)o).getTime());
                    }

                    if (Enum.class.isAssignableFrom(c)) {
                        o = EnumKit.getValueByEnum(o);
                    }

                    if (c == char[].class) {
                        o = new String((char[])((char[])o));
                    }

                    int jdbcType = para.getJdbcType();
                    if (jdbcType != 0) {
                        throw new UnsupportedOperationException(jdbcType + ",默认处理器并未处理此jdbc类型");
                    }

                    ps.setObject(i + 1, o);
                }
            }
        }

    }
}
